<template>
    <div class="" v-if="state !== 'hidden'">

        <el-form ref="form" :model="form" :label-width="'write' == state ? '115px':'auto'"
                 :class="'write' == state ? 'write-form':'read-form'"
                 :label-position="'write' == state ? 'top':'left'">

            <div class="card-wrap flex-column justify-end card-padding"
                 v-for="(fitem, findex) in form.purchaseInfoList" :key="fitem.itemId">

                <div class="card-title-wrap">
                    <span>序号{{ findex + 1 }}</span>
                    <span>
                        <span v-if="findex==0 && form.purchaseNo">采购编号：{{ form.purchaseNo|filterNull }}</span>
                    </span>

                    <div v-if="'write'==state">
                        <i class="el-icon-circle-plus-outline icon_add" @click="add(findex)"><span>新增</span></i>
                        <i v-if="0!=findex" class="el-icon-remove-outline icon_add"
                           @click="sub(findex)"><span>删除</span></i>
                        <i class="el-icon-document-copy icon_add" @click="copy(findex)"><span>复制</span></i>
                    </div>
                </div>

                <el-row :gutter="'write' == state? 130 : 10" style="margin-right: 3%">

                    <el-col :span="24">
                        <span class="mini-title">车辆采购信息</span>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="品牌车系:" prop="seriesId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择品牌车系',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.seriesId, callback)
                                       }:{}">

                            <LinkageSelect2 v-if="'write' == state"
                                            v-model="fitem.modeldata" :key="fitem.modelKey"
                                            :check-strictly="false" style="width: 100%"
                                            @changeNode="linkageChange($event, fitem)"/>

                            <span class="text-bold" v-else>
                                {{ fitem.brandName || '' }}/{{fitem.seriesName || ''}}</span>

                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="车型:" prop="modelId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择车型',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.modelId, callback)
                                       }:{}">
                            <ModelSelect v-if="'write' == state" style="width: 100%" @sel="modeSel($event, fitem)"
                                         :modelData="fitem"/>
                            <span class="text-bold" v-else>{{ fitem.modelName | filterNull }}</span>
                        </el-form-item>
                    </el-col>
                    <!--                    <el-col :span="8">-->
                    <!--                        <el-form-item label="品牌名称:" prop="brandId">-->
                    <!--                            <linkage-select @changeNode="linkageChange(val, fitem)" />-->
                    <!--                        </el-form-item>-->
                    <!--                    </el-col>-->

                    <!--                    <el-col :span="8">-->
                    <!--                        <el-form-item label="配置:" prop="config"-->
                    <!--                                      :rules="'write' == state ? {-->
                    <!--                                         required: true,-->
                    <!--                                         message: '请输入配置',-->
                    <!--                                         trigger: 'blur',-->
                    <!--                                         validator: (rule, value, callback) => validData(rule, fitem.config, callback)-->
                    <!--                                       }:{}">-->
                    <!--                            <el-input v-model="fitem.config" clearable v-if="'write' == state"-->
                    <!--                                      placeholder="请输入配置"></el-input>-->
                    <!--                            <span v-else>{{fitem.config|filterNull}}</span>-->
                    <!--                        </el-form-item>-->
                    <!--                    </el-col>-->

                    <el-col :span="8">
                        <el-form-item label="外观颜色:" prop="exteriorColor"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入外观颜色',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.exteriorColor, callback)
                                       }:{}">
                            <el-input maxlength="50" v-model="fitem.exteriorColor" clearable v-if="'write' == state"
                                      placeholder="请输入外观颜色"></el-input>
                            <span class="text-bold" v-else>{{ fitem.exteriorColor|filterNull }}</span>
                            <!--                            <el-select v-model="fitem.exteriorColor" filterable placeholder="请选择">-->
                            <!--                                <el-option-->
                            <!--                                    v-for="item in colorList"-->
                            <!--                                    :key="item.value"-->
                            <!--                                    :label="item.value"-->
                            <!--                                    :value="item.value">-->
                            <!--                                </el-option>-->
                            <!--                            </el-select>-->

                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="内饰颜色:" prop="interiorColor"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入内饰颜色',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.interiorColor, callback)
                                       }:{}">
                            <el-input maxlength="50" v-model="fitem.interiorColor" clearable v-if="'write' == state"
                                      placeholder="请输入内饰颜色"></el-input>
                            <span class="text-bold" v-else>{{ fitem.interiorColor|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="座位数:" prop="seatNum"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入座位数',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.seatNum, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" clearable type="text"
                                      @input="value=>fitem.seatNum=value.replace(/[^\d]/g,'')" :maxlength="2"
                                      v-model="fitem.seatNum"
                                      placeholder="请输入座位数"></el-input>

<!--                            <el-select filterable clearable v-if="'write' == state" style="width: 100%"-->
<!--                                       v-model="fitem.seatNum" placeholder="请选择">-->
<!--                                <el-option-->
<!--                                    v-for="item in fitem.seatList||[]"-->
<!--                                    :key="item"-->
<!--                                    :label="item"-->
<!--                                    :value="item">-->
<!--                                </el-option>-->
<!--                            </el-select>-->

                            <span v-else>{{ fitem.seatNum|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="燃油类型:" prop="fuelType">
                            <el-select filterable v-if="'write' == state" v-model="fitem.fuelType" clearable
                                       style="width: 100%">
                                <template v-for="dict in dict.type.fuel_type">
                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                                </template>
                            </el-select>
                            <span v-else><dict-tag
                                :options="dict.type.fuel_type"
                                :value="fitem.fuelType"/></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <!--                        <el-form-item label="采购数量" prop="purchaseNum"-->
                        <!--                                      :rules="{-->
                        <!--                                         required: true,-->
                        <!--                                         message: '请输入采购数量',-->
                        <!--                                         trigger: 'blur',-->
                        <!--                                         validator: (rule, value, callback) => validData(rule, fitem.purchaseNum, callback)-->
                        <!--                                       }">-->
                        <!--                            <el-input-number @change="inputChange(findex)" style="width: auto" v-model="fitem.purchaseNum" :min="1"></el-input-number>-->
                        <!--                        </el-form-item>-->

                        <el-form-item label="采购数量:" prop="purchaseNum"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入采购数量',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.purchaseNum, callback)
                                       }:{}">
                            <el-input maxlength="6" v-if="'write' == state"
                                      @change="inputChange(findex, 2)"
                                      type="text"
                                      @input="value=>{fitem.purchaseNum=value.replace(/[^\d]/g,'');$forceUpdate()}"
                                      v-model="fitem.purchaseNum" clearable
                                      placeholder="请输入采购数量"></el-input>
                            <span class="text-bold" v-else>{{ fitem.purchaseNum|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="指导价(元):" prop="guidancePrice"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入指导价',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.guidancePrice, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand :ref="`guidancePrice${fitem.itemId}`"
                                      @change="inputChange(findex)"
                                      @input="value=>{if(isNaN(fitem.guidancePrice)) { fitem.guidancePrice = '' }; if(fitem.guidancePrice.indexOf('.')>0){fitem.guidancePrice=fitem.guidancePrice.slice(0,fitem.guidancePrice.indexOf('.')+3)} fitem.guidancePrice = fitem.guidancePrice.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.guidancePrice" placeholder="请输入指导价"></el-input>
                            <span v-thousand v-else>{{ fitem.guidancePrice|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="采购单价(元):" prop="purchasePrice"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入采购单价',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.purchasePrice, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand
                                      @change="inputChange(findex, 1)"
                                      @input="value=>{if(isNaN(fitem.purchasePrice)) { fitem.purchasePrice = '' };
                                        if(fitem.purchasePrice.indexOf('.')>0){fitem.purchasePrice=fitem.purchasePrice.slice(0,fitem.purchasePrice.indexOf('.')+3)}
                                        fitem.purchasePrice = fitem.purchasePrice.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.purchasePrice" placeholder="请输入采购单价"></el-input>
                            <span v-thousand class="text-bold" v-else>{{ fitem.purchasePrice|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="采购总价(元):" prop="purchaseTotalPrice"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入采购总价',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.purchaseTotalPrice, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand :ref="`purchaseTotalPrice${fitem.itemId}`"
                                      @change="inputChange(findex, 3)"
                                      @input="value=>{if(isNaN(fitem.purchaseTotalPrice)) { fitem.purchaseTotalPrice = '' };
                                        if(fitem.purchaseTotalPrice.indexOf('.')>0){fitem.purchaseTotalPrice=fitem.purchaseTotalPrice.slice(0,fitem.purchaseTotalPrice.indexOf('.')+3)}
                                        fitem.purchaseTotalPrice = fitem.purchaseTotalPrice.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model="fitem.purchaseTotalPrice" placeholder="请输入采购总价"></el-input>
                            <span v-thousand class="text-bold" v-else>{{ fitem.purchaseTotalPrice|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="折扣率:" prop="discountRate"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入折扣率',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.discountRate, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" readonly
                                      v-model.trim="fitem.discountRate" placeholder="请输入指导价和采购单价"></el-input>
                            <span v-else>{{ fitem.discountRate|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="车辆性质:" prop="carNature">
                            <el-select filterable v-if="'write' == state" v-model="fitem.carNature" clearable
                                       style="width: 100%">
                                <template v-for="dict in dict.type.car_nature">
                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                                </template>
                            </el-select>
                            <span v-else><dict-tag
                                :options="dict.type.car_nature"
                                :value="fitem.carNature"/></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="新车/旧车:" prop="carClassification"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择新车/旧车',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.carClassification, callback)
                                       }:{}">
                            <el-select filterable v-if="'write' == state" v-model="fitem.carClassification" clearable
                                       style="width: 100%">
                                <template v-for="dict in dict.type.car_classification">
                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                                </template>
                            </el-select>
                            <span v-else><dict-tag
                                :options="dict.type.car_classification"
                                :value="fitem.carClassification"/></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="供应商名称:" prop="supplierId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择供应商名称',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.supplierId, callback)
                                       }:{}">
                            <el-select
                                @change="spCheck($event, fitem)" filterable
                                v-if="'write' == state" v-model="fitem.supplierId" clearable style="width: 100%">
                                <template v-for="dict in supplierList">
                                    <el-option :label="dict.supplierName" :value="dict.supplierId"
                                               :key="dict.supplierId"></el-option>
                                </template>
                            </el-select>
                            <span v-else>{{ fitem.supplierName|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="开户名称:" prop="accountId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择开户名称',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.accountId, callback)
                                       }:{}">
                            <!--                            <el-input maxlength="50" v-if="'write' == state"-->
                            <!--                                      v-model.trim="fitem.account" placeholder="请输入"></el-input>-->
                            <el-select @change="accountChange($event, fitem)" filterable v-if="'write' == state"
                                       v-model="fitem.accountId" clearable style="width: 100%">
                                <template v-for="dict in fitem.accountList">
                                    <el-option :label="dict.accountName" :value="dict.accountId"
                                               :key="dict.accountId"></el-option>
                                </template>
                            </el-select>
                            <span v-else>{{ fitem.account|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="采购类型:" prop="purchaseType"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择采购类型',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.purchaseType, callback)
                                       }:{}">
                            <el-select filterable v-if="'write' == state" v-model="fitem.purchaseType" clearable
                                       style="width: 100%">
                                <template v-for="dict in dict.type.purchase_type">
                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                                </template>
                            </el-select>
                            <span v-else><dict-tag
                                :options="dict.type.purchase_type"
                                :value="fitem.purchaseType"/></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="进口车/国产车:" prop="domesticImported"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择进口车/国产车',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.domesticImported, callback)
                                       }:{}">
                            <el-select filterable v-if="'write' == state" v-model="fitem.domesticImported" clearable
                                       style="width: 100%">
                                <template v-for="dict in dict.type.domestic_imported">
                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                                </template>
                            </el-select>
                            <span v-else><dict-tag
                                :options="dict.type.domestic_imported"
                                :value="fitem.domesticImported"/></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="车辆产权:" prop="paymentStoreId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择车辆产权',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.paymentStoreId, callback)
                                       }:{}">

                            <el-select filterable v-if="'write' == state" v-model="fitem.paymentStoreId" clearable
                                       style="width: 100%" @change="payStoreChange($event, fitem)">
                                <template v-for="(item, index) in companyList">
                                    <el-option :label="item.deptName" :value="item.deptId" :key="index"></el-option>
                                </template>
                            </el-select>
                            <span class="text-bold" v-else>{{fitem.paymentStore}}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <span class="mini-title">车辆支付信息</span>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="定金:" prop="deposit"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择定金',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.deposit, callback)
                                       }:{}">

                            <el-radio-group v-if="'write' == state" v-model="fitem.deposit">
                                <template v-for="dict in dict.type.deposit">
                                    <el-radio :label="dict.value">{{ dict.label }}</el-radio>
                                </template>
                            </el-radio-group>
                            <span class="text-bold" v-else><dict-tag
                                :options="dict.type.deposit"
                                :value="fitem.deposit"/></span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="1==fitem.deposit">
                        <el-form-item label="定金金额(元/单辆):" prop="singleDepositPrice"
                        >
                            <el-input
                                @change="inputChange(findex, 4)" v-thousand
                                v-if="'write' == state"
                                @input="value=>{if(isNaN(fitem.singleDepositPrice)) { fitem.singleDepositPrice = '' };
                                if(fitem.singleDepositPrice.indexOf('.')>0){fitem.depositPrice=fitem.singleDepositPrice.slice(0,fitem.singleDepositPrice.indexOf('.')+3)}
                                fitem.singleDepositPrice = fitem.singleDepositPrice.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                v-model.trim="fitem.singleDepositPrice" placeholder="请输入定金金额"></el-input>
                            <span v-else v-thousand>{{ fitem.singleDepositPrice|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="1==fitem.deposit">
                        <el-form-item label="余额金额(元/单辆):" prop="singleBalancePrice"
                        >
                            <el-input readonly v-if="'write' == state" disabled v-thousand :ref="`singleBalancePrice${fitem.itemId}`"
                                      v-model.trim="fitem.singleBalancePrice" placeholder="自动计算"></el-input>
                            <span v-else v-thousand>{{ fitem.singleBalancePrice|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="企划计划支付日期:" prop="planPayDate"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择企划计划支付日期',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, fitem.planPayDate, callback)
                                       }:{}">
                            <el-date-picker v-if="'write' == state" v-model="fitem.planPayDate"
                                            type="date"
                                            placeholder="请选择企划计划支付日期"
                                            value-format='yyyy-MM-dd' style="width: 100%;">
                            </el-date-picker>
                            <span class="text-bold" v-else>{{ fitem.planPayDate|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="1==fitem.deposit">
                        <el-form-item label="定金金额总计(元):" prop="depositPrice"
                        >
                            <el-input v-thousand disabled :ref="`depositPrice${fitem.itemId}`"
                                      v-if="'write' == state"
                                      @input="value=>{if(isNaN(fitem.depositPrice)) { fitem.depositPrice = '' };
                                if(fitem.depositPrice.indexOf('.')>0){fitem.depositPrice=fitem.depositPrice.slice(0,fitem.depositPrice.indexOf('.')+3)}
                                fitem.depositPrice = fitem.depositPrice.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.depositPrice" placeholder="自动计算"></el-input>
                            <span v-else v-thousand>{{ fitem.depositPrice|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="1==fitem.deposit">
                        <el-form-item label="余额金额总计(元):" prop="balancePrice"
                        >
                            <el-input readonly v-if="'write' == state" disabled v-thousand :ref="`balancePrice${fitem.itemId}`"
                                      v-model.trim="fitem.balancePrice" placeholder="自动计算"></el-input>
                            <span v-else v-thousand>{{ fitem.balancePrice|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="16">
                        <el-form-item label="备注:" prop="remark">
                            <el-input maxlength="500" v-if="'write' == state" type="textarea" v-model="fitem.remark"
                                      clearable
                                      placeholder="请输入备注"></el-input>
                            <span v-else>{{ fitem.remark|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24" style="margin-top: 15px">
                        <span class="mini-title">其他付款信息</span>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="购置税(元/单辆):" prop="purchaseTax"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入购置税',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.purchaseTax, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand
                                      @input="value=>{if(isNaN(fitem.purchaseTax)) { fitem.purchaseTax = '' };
                                    if(fitem.purchaseTax.indexOf('.')>0){fitem.purchaseTax=fitem.purchaseTax.slice(0,fitem.purchaseTax.indexOf('.')+3)}
                                    fitem.purchaseTax = fitem.purchaseTax.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.purchaseTax" placeholder="请输入购置税"></el-input>
                            <span v-else v-thousand>{{ fitem.purchaseTax|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="上牌费(元/单辆):" prop="registrationFee"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入上牌费',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.registrationFee, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand
                                      @input="value=>{if(isNaN(fitem.registrationFee)) { fitem.registrationFee = '' };
                                    if(fitem.registrationFee.indexOf('.')>0){fitem.registrationFee=fitem.registrationFee.slice(0,fitem.registrationFee.indexOf('.')+3)}
                                    fitem.registrationFee = fitem.registrationFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.registrationFee" placeholder="请输入上牌费"></el-input>
                            <span v-else v-thousand>{{ fitem.registrationFee|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="出库费(元/单辆):" prop="outboundFee"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入出库费',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.outboundFee, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand
                                      @input="value=>{if(isNaN(fitem.outboundFee)) { fitem.outboundFee = '' };
                                    if(fitem.outboundFee.indexOf('.')>0){fitem.outboundFee=fitem.outboundFee.slice(0,fitem.outboundFee.indexOf('.')+3)}
                                    fitem.outboundFee = fitem.outboundFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.outboundFee" placeholder="请输入出库费"></el-input>
                            <span v-else v-thousand>{{ fitem.outboundFee|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="物流费(元/单辆):" prop="logisticsFee"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入物流费',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.logisticsFee, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand
                                      @input="value=>{if(isNaN(fitem.logisticsFee)) { fitem.logisticsFee = '' };
                                    if(fitem.logisticsFee.indexOf('.')>0){fitem.logisticsFee=fitem.logisticsFee.slice(0,fitem.logisticsFee.indexOf('.')+3)}
                                    fitem.logisticsFee = fitem.logisticsFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.logisticsFee" placeholder="请输入物流费"></el-input>
                            <span v-else v-thousand>{{ fitem.logisticsFee|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="其他加装费(元/单辆):" prop="retrofittingFee"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请输入其他加装费',
                                         trigger: 'blur',
                                         validator: (rule, value, callback) => validData(rule, fitem.retrofittingFee, callback)
                                       }:{}">
                            <el-input v-if="'write' == state" v-thousand
                                      @input="value=>{if(isNaN(fitem.retrofittingFee)) { fitem.retrofittingFee = '' };
                                    if(fitem.retrofittingFee.indexOf('.')>0){fitem.retrofittingFee=fitem.retrofittingFee.slice(0,fitem.retrofittingFee.indexOf('.')+3)}
                                    fitem.retrofittingFee = fitem.retrofittingFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                      v-model.trim="fitem.retrofittingFee" placeholder="请输入其他加装费"></el-input>
                            <span v-else v-thousand>{{ fitem.retrofittingFee|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                </el-row>

            </div>

            <div class="card-wrap flex-column justify-end card-padding">

                <!--                <el-form ref="form" :model="form" label-width="80px"-->
                <!--                         label-position="top">-->

                <el-row :gutter="'write' == state? 130 : 10" style="margin-right: 3%">

                    <el-col :span="24">
                        <el-form-item label="附件上传:" prop="attachment" style="width: 100%">

                            <ImageCommon :disabled="'write' != state" :up-type="2" info="选择附件" :limit="9"
                                         v-model="form.attachment"></ImageCommon>

                            <!--                                <FileUpload v-model="form.attachment"></FileUpload>-->
                        </el-form-item>
                    </el-col>

                    <el-col :span="18">
                        <el-form-item label="审批附言:" prop="approvalPostscript">
                            <el-input maxlength="500" v-if="'write' == state" type="textarea"
                                      v-model="form.approvalPostscript" clearable
                                      placeholder="请输入审批附言"></el-input>
                            <span v-else>{{ form.approvalPostscript|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" v-if="form.createDate">
                        <el-form-item label="创建日期:" prop="createDate"
                        >
                            <span class="text-bold">{{ form.createDate|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                </el-row>

                <!--                </el-form>-->

            </div>

        </el-form>

        <!--        <div class="card-wrap flex justify-end card-padding">-->
        <!--            <el-button :loading="buttonLoading" type="primary" @click="submitForm(1)">保存</el-button>-->
        <!--            <el-button @click="cancel">取消</el-button>-->
        <!--            <el-button :loading="buttonLoading" type="primary" @click="submitForm(2)">提交</el-button>-->
        <!--        </div>-->

        <el-dialog
            title="选择组织"
            :visible.sync="dialogVisible"
            width="35%">
            <div class="head-container">
                <el-tree
                    :data="deptOptions"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                    ref="tree"
                    node-key="id"
                    default-expand-all
                    highlight-current
                    @node-click="handleNodeClick"
                />
            </div>
        </el-dialog>

        <el-dialog :visible.sync="showBrand" width="35%">

            <linkage-select @changeNode="linkageChange(val, fitem)"/>

            <!--            <city-select v-model="citySelection" placeholder="选择城市" ref="citySelect" :showAllLevels="false"-->
            <!--                         @change="citySelectionChange" v-if="isEdit"></city-select>-->

            <span slot="footer">
                <el-button @click="showBrand=false" size="mini">取 消</el-button>
                <el-button type="primary" size="mini" @click="okBrand">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>


import {deptTreeSelect, listUser} from "@/api/system/user";
import {
    purchaseAdd,
    purchaseUpdate,
    purchaseDetail,
    queryParamList,
    supplierAccount,
    recognitionModel
} from "@/api/purchaseManage/purchaseList";
import {v1 as uuid_v1} from 'uuid'
import LinkageSelect from "@/views/components/linkageSelect.vue";
import LinkageSelect2 from "@/views/components/linkageSelect2.vue";
import ModelSelect from "@/views/components/modelSelect.vue";
import LinkageSelectSearch from "@/views/components/linkageSelectSearch.vue";
import {supplierAllList, supplierList} from "@/api/memberManage/vendorList";
import citySelect from "@/views/components/citySelect.vue";
import {listDept} from "@/api/system/dept";

export default {
    components: {citySelect, LinkageSelect, LinkageSelect2, ModelSelect, LinkageSelectSearch},
    dicts: ['car_nature', 'car_classification', 'purchase_type', 'deposit', 'domestic_imported', 'fuel_type'],
    props: {
        value: {
            default: {},
        },
        state: {
            default: "write",
        },
    },
    computed: {
        form: {
            get() {
                return this.value;
            },
            set(value) {
                this.$emit("input", value);
            },
        },
        watchPurchaseInfoList() {
            return this.form.purchaseInfoList;
        }
    },
    watch: {
        watchPurchaseInfoList: {
            handler(newVal, oldVal) {
                if (this.isFirstChange && this.form.purchaseInfoList && this.form.purchaseInfoList.length>0) {
                    this.isFirstChange = false
                    // console.log('进来了。。。')
                    for (const forElement of this.form.purchaseInfoList) {
                        // this.getSeatList(forElement)

                        this.getSpList(forElement.supplierId, forElement)

                        this.$nextTick(() => {
                            forElement.itemId = uuid_v1()

                            forElement.modeldata = []
                            forElement.modelKey = 0
                            if (forElement.modelId && forElement.modelId != null) {
                                //下标0为一级菜单value
                                forElement.modeldata[0] = String(forElement.brandId);
                                //下标1为二级菜单value
                                forElement.modeldata[1] = String(forElement.seriesId);
                                //下标1为三级菜单value
                                // forElement.modeldata[2] = String(forElement.modelId);
                                forElement.modelKey++
                            }
                            // console.log('-->', forElement.modeldata)
                            this.$forceUpdate()
                        })
                    }
                }
            },
            deep: true,
            immediate: true,
        },
    },
    data() {
        return {
            isFirstChange: true,
            showBrand: false,
            buttonLoading: false,
            // form: {
            //     followerIds: null,
            //     purchaseInfoList: [{
            //         itemId: uuid_v1()
            //     }]
            // },
            supplierList: [],
            dialogVisible: false,
            deptOptions: null,
            defaultProps: {
                children: "children",
                label: "label"
            },
            deptId: null,
            deptLabel: null,
            userList: [],
            spAccounts: [],
            companyList: [],
        };
    },
    created() {
        // this.getDeptTree()
        // this.getUserList()
        this.getSupplierList()
        this.getBelongCompany()
    },
    mounted() {
        // console.log('/clues/clues/{cluesId}==>', this.$route.query)
        // if (this.$route.query && this.$route.query.purchaseOrderId) {
        //     this.getOldData(this.$route.query.purchaseOrderId)
        // }
    },
    methods: {

        getBelongCompany() {
            listDept(
                {
                    deptType: '2',//组织类型（1部门 2公司）
                    // regionId: this.form.cityId,//所在城市（省市区id）
                }).then(res => {
                this.companyList = res.data
            })
        },

        payStoreChange(val, fitem){
            let find = this.companyList.find(item=>val==item.deptId);
            if(find){
                fitem.paymentStore=find.deptName
            }else {
                fitem.paymentStore=null
            }
            this.$forceUpdate()
        },

        spCheck(val, fitem) {
            // fitem.accountList = []
            fitem.accountId = null
            fitem.account = null
            if (val) {
                this.getSpList(val, fitem)
            } else {
                fitem.accountList = []
            }


            let find = this.supplierList.find(item => val == item.supplierId);
            if (find) {
                fitem.supplierName = find.supplierName
            } else {
                fitem.supplierName = null
            }
            this.$forceUpdate()
        },
        getSpList(val, fitem) {
            if (val == undefined || val == null || val == '') {
                return
            }

            supplierAccount(val).then(res => {
                fitem.accountList = res.data

                this.$forceUpdate()
            })
        },
        accountChange(val, fitem) {
            let find = fitem.accountList.find(item => val == item.accountId);
            if (find) {
                fitem.account = find.accountName
            } else {
                fitem.account = null
            }
            this.$forceUpdate()
        },

        getSupplier(code) {
            return this.supplierList.find(item => item.supplierId == code)?.supplierName ?? '--'
        },
        okBrand() {
            if (this.checkedNodesList) {
                this.detailForm.indexBelongCity = this.checkedNodesList.label
                this.detailForm.indexBelongCityId = this.checkedNodesList.value
                this.detailForm.areaName = this.checkedNodesList.pv
                this.detailForm.areaNameId = this.checkedNodesList.pl
            }
            this.showBrand = false
        },
        inputChange(findex, type) {
            findex = Number(findex)
            // console.log('数量', this.form.purchaseInfoList[findex].purchaseNum, '--单价--', this.form.purchaseInfoList[findex].purchasePrice)

            if(1 === type || 2 === type){
                if (this.form.purchaseInfoList[findex].purchaseNum && this.form.purchaseInfoList[findex].purchasePrice) {
                    this.$set(this.form.purchaseInfoList[findex], 'purchaseTotalPrice', Number(this.form.purchaseInfoList[findex].purchaseNum * this.form.purchaseInfoList[findex].purchasePrice).toFixed(2))
                    // this.form.purchaseInfoList[findex].purchaseTotalPrice = Number(this.form.purchaseInfoList[findex].purchaseNum * this.form.purchaseInfoList[findex].purchasePrice).toFixed(2)
                } else {
                    this.$set(this.form.purchaseInfoList[findex], 'purchaseTotalPrice', null)
                    // this.form.purchaseInfoList[findex].purchaseTotalPrice = null
                }
            }

            //数量 * 定金单辆 = 定金总计
            if (this.form.purchaseInfoList[findex].purchaseNum && this.form.purchaseInfoList[findex].singleDepositPrice) {
                this.$set(this.form.purchaseInfoList[findex], 'depositPrice', Number(this.form.purchaseInfoList[findex].purchaseNum * this.form.purchaseInfoList[findex].singleDepositPrice).toFixed(2))
            }else {
                this.$set(this.form.purchaseInfoList[findex], 'depositPrice', null)
            }

            //单价 - 定金单辆 = 余额单辆
            if (this.form.purchaseInfoList[findex].purchasePrice && this.form.purchaseInfoList[findex].singleDepositPrice) {
                this.$set(this.form.purchaseInfoList[findex], 'singleBalancePrice', Number(this.form.purchaseInfoList[findex].purchasePrice - this.form.purchaseInfoList[findex].singleDepositPrice).toFixed(2))
            }else {
                this.$set(this.form.purchaseInfoList[findex], 'singleBalancePrice', null)
            }

            //数量 * 余额单辆 = 余额总计
            if (this.form.purchaseInfoList[findex].purchaseNum && this.form.purchaseInfoList[findex].singleBalancePrice) {
                this.$set(this.form.purchaseInfoList[findex], 'balancePrice', Number(this.form.purchaseInfoList[findex].purchaseNum * this.form.purchaseInfoList[findex].singleBalancePrice).toFixed(2))
            }else {
                this.$set(this.form.purchaseInfoList[findex], 'balancePrice', null)
            }


            // if (this.form.purchaseInfoList[findex].depositPrice && this.form.purchaseInfoList[findex].purchaseTotalPrice) {
            //     this.form.purchaseInfoList[findex].balancePrice = Number(this.form.purchaseInfoList[findex].purchaseTotalPrice - this.form.purchaseInfoList[findex].depositPrice).toFixed(2)
            // } else {
            //     this.form.purchaseInfoList[findex].balancePrice = null
            // }

            if (this.form.purchaseInfoList[findex].guidancePrice && this.form.purchaseInfoList[findex].purchasePrice) {
                this.$set(this.form.purchaseInfoList[findex], 'discountRate', Math.round(((Number(this.form.purchaseInfoList[findex].guidancePrice - this.form.purchaseInfoList[findex].purchasePrice)) / Number(this.form.purchaseInfoList[findex].guidancePrice) * 100)) + "%")
            } else {
                this.$set(this.form.purchaseInfoList[findex], 'discountRate', null)
            }

            this.$forceUpdate()

            //单价1    数量2    总价3   定金4
            if(1 === type || 2 === type) {
                this.$nextTick(() => {
                    let el = this.$refs[`purchaseTotalPrice${this.form.purchaseInfoList[findex].itemId}`]
                    el[0].$refs.input.dispatchEvent(new Event('blur'));
                })
            }

            if(2 === type || 4 === type){
                this.$nextTick(() => {
                    let el2 = this.$refs[`depositPrice${this.form.purchaseInfoList[findex].itemId}`]
                    if(el2 && el2.length>0){
                        el2[0]?.$refs?.input?.dispatchEvent(new Event('blur'));
                    }
                })
            }

            if(1 === type || 4 === type){
                this.$nextTick(() => {
                    let el2 = this.$refs[`singleBalancePrice${this.form.purchaseInfoList[findex].itemId}`]
                    if(el2 && el2.length>0){
                        el2[0]?.$refs?.input?.dispatchEvent(new Event('blur'));
                    }
                })
            }

            if(1 === type || 2 === type || 4 === type){
                this.$nextTick(() => {
                    let el2 = this.$refs[`balancePrice${this.form.purchaseInfoList[findex].itemId}`]
                    if(el2 && el2.length>0){
                        el2[0]?.$refs?.input?.dispatchEvent(new Event('blur'));
                    }
                })
            }


        },

        validData(rule, value, callback) {
            // console.log('aaa', rule, value, callback)
            if (rule.required && !value) {
                // this.$modal.msgError(`未填写${value}`);
                callback(new Error(rule.message));
            } else {
                callback();
            }
        },

        getSupplierList() {
            supplierAllList({approvedFlag: true, availableStatus: 0, businessTypeCode:1}).then(res => {
                if (res.code == "200") {
                    const {data, total} = res
                    this.supplierList = data
                }
            });
        },

        modeSel(val, fitem){
            // console.log('modeSel', val, fitem)
            if (val && val.modelId) {
                if(val.seriesId != fitem.seriesId){
                    this.$set(fitem, 'modeldata', [])
                    this.$set(fitem.modeldata, 0, String(val.brandId))
                    this.$set(fitem.modeldata, 1, String(val.seriesId))
                    this.$set(fitem, 'modelKey', fitem.modelKey+1)
                }

                this.$set(fitem, 'brandId', val.brandId)
                this.$set(fitem, 'seriesId', val.seriesId)
                this.$set(fitem, 'brandName', val.brandName)
                this.$set(fitem, 'seriesName', val.seriesName)

                this.$set(fitem, 'modelId', val.modelId)
                this.$set(fitem, 'modelName', val.modelName)

                // fitem.modeldata = []
                // fitem.modeldata[0] = String(fitem.brandId);
                // //下标1为二级菜单value
                // fitem.modeldata[1] = String(fitem.seriesId);
                //下标1为三级菜单value
                // fitem.modeldata[2] = fitem.modelId;
                // fitem.modelKey++
            } else {
                fitem.modelId = null
                fitem.modelName = null
            }


            this.getSeatList(fitem)
            this.$forceUpdate()
            this.$refs.form.validateField(["seriesId", "modelId"]);
            this.$nextTick(()=>{
                this.$refs.form.validateField(["seriesId", "modelId"]);
            })
        },

        async linkageChange(val, fitem) {
            this.$set(fitem, 'modeldata', [])

            if (val && val[1] && val[1].id) {
                this.$set(fitem, 'brandId', val[0].id)
                this.$set(fitem, 'seriesId', val[1].id)
                this.$set(fitem, 'brandName', val[0].name)
                this.$set(fitem, 'seriesName', val[1].name)

                this.$set(fitem.modeldata, 0, String(fitem.brandId))
                this.$set(fitem.modeldata, 1, String(fitem.seriesId))
            } else {
                this.$set(fitem, 'brandId', null)
                this.$set(fitem, 'seriesId', null)
                this.$set(fitem, 'brandName', null)
                this.$set(fitem, 'seriesName', null)
            }
            this.$set(fitem, 'modelId', null)
            this.$set(fitem, 'modelName', null)

            // console.log('linkageChange', val, fitem)

            this.$forceUpdate()
            this.$refs.form.validateField(["seriesId", "modelId"]);
            this.$nextTick(()=>{
                this.$refs.form.validateField(["seriesId", "modelId"]);
            })
        },

        getColorList(fitem) {
            queryParamList({modelId: fitem.modelId, type: 1}).then(res => {
                this.$set(fitem, 'colorList', res.map(item => item.color))
                // fitem.colorList = res.map(item=>item.color)
            })
        },

        getSeatList(fitem) {
            if (fitem.modelId == undefined || fitem.modelId == null || fitem.modelId == '') {
                return
            }

            let that = this

            // queryParamList({modelId: fitem.modelId, type: 2}).then(res => {
            //     this.$set(fitem, 'seatList', res.map(item => item.seatNumber))
            //     // fitem.seatList = res.map(item => item.seatNumber)
            //
            //
            //     that.$nextTick(() => {
            //         that.$forceUpdate()
            //     })
            // })

            recognitionModel(fitem.modelId).then(res=>{
                if (res.code == '200') {
                    for (const dataKey in res.data) {
                        if (res.data[dataKey] != undefined && res.data[dataKey] != null && res.data[dataKey] != '') {
                            // fitem[dataKey] = res.data[dataKey]
                            that.$set(fitem, dataKey, res.data[dataKey])
                        }
                    }
                }

                that.$nextTick(() => {
                    that.$forceUpdate()

                    // this.$nextTick(() => {
                        let el = that.$refs[`guidancePrice${fitem.itemId}`]
                        // console.log('el', el)
                        el[0].$refs.input.dispatchEvent(new Event('focus'));
                        el[0].$refs.input.dispatchEvent(new Event('blur'));
                    // })

                })
            })

        },

        add(index) {
            this.form.purchaseInfoList.splice(index + 1, 0, {
                itemId: uuid_v1(),
                modelKey:0
            })
            this.$forceUpdate()
        },
        sub(index) {
            this.form.purchaseInfoList.splice(index, 1)
            this.$forceUpdate()
        },
        copy(index) {
            this.$modal.msgSuccess("已复制");
            if (this.form.purchaseInfoList.length - index > 1) {
                // this.form.purchaseInfoList[index + 1] = {
                //     ...this.form.purchaseInfoList[index],
                //     itemId: this.form.purchaseInfoList[index + 1].itemId,
                //     purchaseInfoId: null,
                //     modelKey:this.form.purchaseInfoList[index]+1
                // }

                this.$set(this.form.purchaseInfoList, index+1, {
                    ...this.form.purchaseInfoList[index],
                    itemId: this.form.purchaseInfoList[index + 1].itemId,
                    purchaseInfoId: null,
                    // modelKey:this.form.purchaseInfoList[index]+1
                })


                // console.log('this.form.purchaseInfoList', this.form.purchaseInfoList)

                this.$forceUpdate()
            }
        },
        cancel() {
            this.$router.back();
            this.$store.dispatch('tagsView/delView', this.$route);
        },

        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        /** 查询组织下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        // 节点单击事件
        handleNodeClick(data) {
            // console.log('data', data)

            this.deptLabel = data.label
            this.deptId = data.id;
            this.form.followerIds = null;

            this.dialogVisible = false;

            this.getUserList();
        },
        getUserList() {
            listUser({
                pageNum: 1,
                pageSize: 100000,
                deptId: this.deptId
            }).then(response => {
                    this.userList = response.rows;
                    // this.total = response.total;
                    // this.loading = false;
                }
            );
        },
        deptClick() {
            this.dialogVisible = true
            this.$refs.deptselect.blur()
        },
        async valid() {
            return new Promise((resolve) => {
                if ('write' == this.state) {
                    this.$refs["form"].validate(valid => {
                        if(!valid){
                            this.$modal.msgError("必填项未填写")
                        }

                        resolve(valid);
                    });
                } else {
                    resolve(true)
                }
            })
        },
    }
};
</script>


<style lang="scss" scoped>

.write-form .el-form-item {
    margin-bottom: 13px !important;
    width: 100%;
}

::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}


.icon_add {
    margin-left: 10px;
    cursor: pointer;
}

::v-deep .read-form .el-form-item__label-wrap,
::v-deep .read-form .el-form-item__content {
    margin-left: 0 !important;
}

.text-bold{
    font-weight: bold;//改了之后发现不好看
    //color: #00afff;
}

.mini-title{
    font-size: 15px;
}


//::v-deep .el-input__inner {
//    background-color: transparent !important;
//    border: none !important;
//    height: 32px !important;
//    font-size: 12px !important;
//    //color: #333 !important;
//}
//::v-deep .el-textarea__inner {
//    background-color: #000 !important;
//    border: 1px solid #eee !important;
//    height: 88px !important;
//    color: #fff !important;
//}

</style>
